﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SkyConnector.Model
{
    public class localConnection
    {
        private Socket m_clientSocket;
        private string recvStr;

        public localConnection(Socket clientSocket, Boolean asynchronously)
        {
            m_clientSocket = clientSocket;

            if (asynchronously)
                new Thread(ProcessRequest).Start();
            else ProcessRequest();
        }

        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            using (m_clientSocket)
            {
                var buffer = new Byte[1024];
                if (m_clientSocket.Poll(5 * c_microsecondsPerSecond, SelectMode.SelectRead))
                {
                    if (m_clientSocket.Available == 0)
                        return;

                    Int32 bytesRead = m_clientSocket.Receive(buffer, m_clientSocket.Available, SocketFlags.None);

                    recvStr = new string(Encoding.UTF8.GetChars(buffer));
                }
            }
        }

        public int getReceivedInteger()
        {
            try
            {
                return int.Parse(recvStr);
            }
            
            catch (Exception)
            {
                return -1;
            }
        }
    }
}
